package com.atguigu.spzx.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.atguigu.spzx.model.pojo.h5.UserInfo;
import com.atguigu.spzx.user.client.UserFeignClient;
import com.atguigu.spzx.utils.DYLAssert;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.Ordered;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.concurrent.CompletableFuture;

@Component
public class LoginAuthFilter implements GlobalFilter, Ordered {

    @Autowired
    @Lazy
    private UserFeignClient userFeignClient;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("网关过滤器拦截。。。");
        ServerHttpRequest request = exchange.getRequest();
        RequestPath path = request.getPath();
        boolean match = new AntPathMatcher().match("/api/**/auth/**", path.toString());
        // 判断路径是否放行
        if (!match) {
            return chain.filter(exchange);
        }
        List<String> tokens = request.getHeaders().get("token");
        DYLAssert.isTrue(tokens != null, "token不能为空");
        String token = tokens.get(0);
        DYLAssert.isTrue(StringUtils.isNotEmpty(token), "token不能为空");

        // 连接用户中心，由token获取用户信息
        // 异步线程获取userInfo
        UserInfo userInfo = null;
        try {
            userInfo = CompletableFuture.supplyAsync(()-> userFeignClient.getUserInfoByToken(token)).get();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        // 返回鉴权结果
        ServerHttpRequest newRequest = request.mutate().header("userJson", JSON.toJSONString(userInfo, SerializerFeature.BrowserSecure)).build();
        exchange.mutate().request(newRequest).build();
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
